package com.hatricks.algorithm.leetcode.inversionofthelist_206;

/**
 * @packageName: com.hatricks.algorithm.leetcode.inversionofthelist_206
 * @className: InvertLinkedList
 * @author: yanyuhui yanyuhui@chinasofti.com
 * @date: 2021/6/29 17:41
 * @link https://leetcode-cn.com/problems/reverse-linked-list/
 * @description: 反转链表
 */
class Solution {

    public static void main(String[] args) {
        ListNode first = new ListNode();
        ListNode second = new ListNode(1, first);
        ListNode third = new ListNode(2, second);
        System.out.println(reverseList(third));
    }

    /**
     * 反转单链表
     *
     * @param head 头结点
     * @return 反转之后的链表
     */
    public static ListNode reverseList(ListNode head) {
        ListNode newHead = null;
        ListNode current = head;
        while (current != null) {
            //将链表的下一个节点存储起来,做后续条件
            final ListNode next = current.next;
            // 当前节点下一个指针往前赋值
            current.next = newHead;
            /*
             * JAVA将指针的概念封装之后,这里的首节点prev为NULL
             */
            // 给新链表将当前节点赋值过来
            newHead = current;
            //便利条件赋值
            current = next;
        }
        return newHead;
    }


    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }

        @Override
        public String toString() {
            return "ListNode{" +
                    "val=" + val +
                    ", next=" + next +
                    '}';
        }
    }
}
